package com.keur.money.ui.market.impl

import android.content.Context
import com.keur.money.R
import com.keur.money.app.MyApp
import com.keur.money.config.KeurConfigs
import com.keur.money.http.ApiService
import com.keur.money.http.ApiService.addCommonParams
import com.keur.money.http.ApiService.addRandomParams
import com.keur.money.http.HttpHelper
import com.keur.money.http.IHttpCallback
import com.keur.money.mvp.presenter.MvpPresenter
import com.keur.money.ui.market.view.IKeurRepayView
import com.keur.money.utils.DateUtils
import com.keur.money.utils.helper.SharedHelper
import org.json.JSONArray
import org.json.JSONObject

/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/8/7 13:45
 * @Annotation：还款信息 Presenter 实现
 */
class KeurRepayPresenterImpl(context: Context?) : MvpPresenter<IKeurRepayView>(context) {

    //待还款信息
    var repayInfo: JSONObject? = null
    //优惠券列表
    private var couponList: ArrayList<JSONObject>? = null
    //选择的优惠券信息
    private var selectCoupon: JSONObject? = null

    /**
     * 选择优惠券
     */
    fun onMullaChooseCouponAction(){
        couponList?.let {
            if (it.size > 0){
                mvpView?.showMullaUserCouponList(it)
            }
        }
    }

    /**
     * 设置选择的优惠券
     */
    fun onMullaSetSelectCouponInfo(obj: JSONObject?){
        selectCoupon = obj
    }

    /**
     * 获取还款信息
     */
    fun loadMullaRepayInfoAction(){
        val httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_REPAYMENT_INFO_PATH)
        val params = JSONObject().addCommonParams().addRandomParams()
        params.put("product",mvpView?.loadProductName())
        params.put("token",mvpView?.loadProductToken())
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null) {
                            repayInfo = obj
                            mvpView?.showMullaRepayInfo(obj)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showMullaToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }

    /**
     * 获取优惠券列表
     */
    fun loadMullaUserCouponListAction(){
        if (couponList == null){
            couponList = arrayListOf()
        }
        couponList?.clear()
        val dataString = SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_USER_COUPON_INFO)
        if (dataString.isNotEmpty()){
            val couponArray = JSONArray(dataString)
            if (couponArray.length() > 0){
                repayInfo?.let {
                    //待还金额
                    val repayAmount = it.optLong("repayAmount")
                    //到账金额
                    val receivedAmount = it.optLong("realAmount")
                    for (i in 0..<couponArray.length()){
                        val item = couponArray.optJSONObject(i)
                        val couponInfo = JSONObject(item.optString("couponInfo"))
                        //优惠券满足金额
                        val fullAmount = couponInfo.optLong("fullAmount")
                        //优惠券抵扣金额
                        val discountAmount = couponInfo.optLong("amount")
                        //待还金额 < 优惠券满足金额 -> 不可用
                        if (repayAmount < fullAmount){
                            item.put("isAvailable",false)
                            item.put("unavailableReason", MyApp.app.getString(R.string.coupon_use_dialog_unavailable_total))
                        } else {
                            //待还款金额 - 实际到账金额 < 优惠券抵扣金额  -> 不可用
                            if (repayAmount - receivedAmount < discountAmount){
                                item.put("isAvailable",false)
                                item.put("unavailableReason",MyApp.app.getString(R.string.coupon_use_dialog_unavailable_discount))
                            } else {
                                item.put("isAvailable",true)
                            }
                        }
                        val validitytTime = item.optLong("validitytTime") * 1000
                        item.put("expiresTime", DateUtils.getFormatTime(validitytTime,"dd/MM/yyyy"))
                        item.put("daysLeft",DateUtils.getDaysFromTimestamps(System.currentTimeMillis(),validitytTime))
                        couponList?.add(item)
                    }
                }
            }
        }
        couponList?.let {
            if (it.size > 0){
                var maxAmount = 0L
                for (i in 0..<it.size){
                    val item = it[i]
                    if (!item.optBoolean("isAvailable",false)){
                        continue
                    }
                    val couponInfo = JSONObject(item.optString("couponInfo"))
                    val amount = couponInfo.optLong("amount")
                    //筛选选出可用的最大金额
                    if (amount > maxAmount){
                        maxAmount = amount
                    }
                }

                for (i in 0..<it.size){
                    val item = it[i]
                    if (!item.optBoolean("isAvailable",false)){
                        continue
                    }
                    val couponInfo = JSONObject(item.optString("couponInfo"))
                    val amount = couponInfo.optLong("amount")
                    if (amount == maxAmount){
                        item.put("isSelect",true)
                        onMullaSetSelectCouponInfo(item)
                        break
                    }
                }
            }
        }
        mvpView?.showMullaDufauleUseCouponInfo(selectCoupon)
    }

    /**
     * 订单还款
     * 不减免 normal
     * 积分减免 score
     * 优惠券减免 coupon
     */
    fun loadMullaPayLinkAction(){
        var httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_REPAYMENT_URL_PATH)
        if (KeurConfigs.isUgx() || KeurConfigs.isKsh()){//肯尼亚、乌干达 需要使用 getOrderRepayH5 获取链接
            httpUrl = ApiService.getHttpUrl(ApiService.API_PATH.KEUR_API_REPAYMENT_KSH_UGX_URL_PATH)
        }
        val params = JSONObject().addCommonParams().addRandomParams().apply {
            put("product",mvpView?.loadProductName())
            put("token",mvpView?.loadProductToken())
            put("mobile",SharedHelper.getKeurSPString(SharedHelper.KEUR_SPKEY.KEUR_MOBILE))
        }
        var couponId = ""
        selectCoupon?.let {
            couponId = it.optString("id")
            params.put("annulType","coupon")
            params.put("couponId",couponId)
        }
        HttpHelper.postKeurAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                mvpView?.hideMullaLoading()
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        if (obj != null){
                            var linkUrl = ""
                            val url = obj.optString("url")
                            if (url.isNotEmpty()){
                                linkUrl = url
                            }

                            val repayUrl = obj.optString("repayUrl")
                            if (repayUrl.isNotEmpty()){
                                linkUrl = repayUrl
                            }

                            //没有还款链接 - 需要进入还款状态页查询还款状态
                            if (linkUrl.isEmpty()){
                                val thirdOrderId = obj.optString("thirdOrderId")
                                mvpView?.showMullaPaymentStatusPage(thirdOrderId,couponId)
                            } else {
                                mvpView?.showMullaPayLink(linkUrl)
                            }
                        }
                    }
                    else -> {
                        mvpView?.showMullaToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showMullaToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideMullaLoading()
            }
        })
    }
}